package stdio.costa.imoca.spi;

import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import stdio.costa.imoca.dao.MocaUserDao;
import stdio.costa.imoca.exception.MocaUserValidationException;
import stdio.costa.imoca.model.MocaUser;
import stdio.costa.imoca.utils.Constants;

@Component
public class MocaUserSpi {

	@Autowired
	private MocaUserDao mocaUserDao;

	// should add "throw exception"
	public MocaUser getMocaUserByAccessToken(String accessTokenCode) {
		try {
			// should add validation
			String[] strs = accessTokenCode.split(Constants.SPLITER);
			// big problem here
			if (Constants.WEIBO.equals(strs[0])) {
				return mocaUserDao.findUserByWeiboUidAndAccessToken(strs[1],
						strs[2]);
			} else if (Constants.QQ.equals(strs[0])) {
				return mocaUserDao.findUserByQQUidAndAccessToken(
						Long.parseLong(strs[1]), strs[2]);
			} else if (Constants.MOCA.equals(strs[0])) {
				return mocaUserDao.findUserByUuidAndPassword(strs[1], strs[2]);
			}
		} catch (Exception ex) {
			ex.printStackTrace();
			return null;
		}
		return null;
	}

	public MocaUser findUserByWeiboUid(String weiboUid) {
		return mocaUserDao.findUserByWeiboUid(weiboUid);
	}

	public MocaUser findUserByQQUid(String qqUid) {
		return mocaUserDao.findUserByQQUid(qqUid);
	}

	public MocaUser findUserByNameOrEmailOrPhone(String name, String email,
			String phone) {
		
		MocaUser mocaUser = mocaUserDao.findUserByNameOrEmailOrPhone(name, email, phone);
		
		return mocaUser;
	}

	public void save(MocaUser mocaUser) {
		mocaUserDao.save(mocaUser);
	}

	public MocaUser updateWeiboAccessToken(MocaUser mocaUser) {
		return mocaUserDao.updateWeiboAccessToken(mocaUser);
	}

	public MocaUser loginByUsername(String username, String password) {
		MocaUser mocaUser = mocaUserDao.findUserByName(username);
		if (mocaUser != null && mocaUser.getPassword().equals(DigestUtils.md5Hex(password))) {
			return mocaUser;
		}
		return null;
	}

	public MocaUser loginByEmail(String email, String password) {
		MocaUser mocaUser = mocaUserDao.findUserByEmail(email);
		if (mocaUser != null && mocaUser.getPassword().equals(DigestUtils.md5Hex(password))) {
			return mocaUser;
		}
		return null;
	}

	public MocaUser loginByPhone(String phone, String password) {
		MocaUser mocaUser = mocaUserDao.findUserByPhone(phone);
		if (mocaUser != null && mocaUser.getPassword().equals(DigestUtils.md5Hex(password))) {
			return mocaUser;
		}
		return null;
	}
}
